package com.yilong.wei.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yilong.wei.app.domain.Country;
import com.yilong.wei.app.domain.MenuDO;
import com.yilong.wei.app.domain.Respond;
import com.yilong.wei.app.domain.Tree;
import com.yilong.wei.app.service.CountryService;
import com.yilong.wei.app.service.MenuService;
import com.yilong.wei.app.utils.LocalDateTimeUtils;
import com.yilong.wei.app.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Controller
@RequestMapping("country")
public class CountryController {

    private static final Logger logger = LoggerFactory.getLogger(CountryController.class);

    @Autowired
    private CountryService countryService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/getList")
    @ResponseBody

/**
 * 
 * [request]
 * @return com.yilong.wei.app.domain.Respond
 * @author SOS
 * @creed: Talk is cheap,show me the code
 * @date 2019/6/14 16:04
 */

    public Respond list(HttpServletRequest request){
        Respond respond = new Respond();
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
//        ValueOperations valueOperations = redisTemplate.opsForValue();
//        String key = "listKey_"+page+"_" + limit;
//        if (redisTemplate.hasKey(key)) {
//            logger.info("从Redis中获取key:{}",key);
//            PageInfo<Country> pageInfo = (PageInfo<Country>) valueOperations.get(key);
//            respond.setCode(200);
//            respond.setMsg("请求成功...");
//            respond.setData(pageInfo.getList());
//            respond.setCount(pageInfo == null ? 0 : (int)pageInfo.getTotal());
//            return respond;
//        }
        PageHelper.startPage(Integer.parseInt(page),Integer.parseInt(limit));
        List<Country> list = countryService.findAll();
        PageInfo<Country> pageInfo = new PageInfo(list);
        logger.info("执行方法:{},执行时间:{}","getList", LocalDateTimeUtils.getNowTime());
//        return JSONObject.toJSONString(pageInfo);
        List<Country> pageInfoList = pageInfo.getList();
//        valueOperations.set(key,pageInfo,30, TimeUnit.MINUTES);
        respond.setCode(200);
        respond.setMsg("请求成功...");
        respond.setCount(pageInfo == null ? 0 : (int)pageInfo.getTotal());
        respond.setData(pageInfoList);
        return respond;
    }


    @RequestMapping(value = "/edit")
    @ResponseBody
    public Respond edit(Country country){
        Respond respond = new Respond();
        String key = "key_"+country.getCode();
        try {
            logger.info("执行方法:{},执行时间:{}","edit",LocalDateTimeUtils.getNowTime());
            if (redisTemplate.hasKey(key)) {
                redisTemplate.delete(key);
            }
            int i = countryService.updateByPrimaryKey(country);
            respond.setMsg("执行成功..");
            respond.setCode(200);
        } catch (Exception e) {
            e.printStackTrace();
            respond.setCode(0);
            respond.setMsg("请求成功...");
            respond.setCount(0);
        }


        return respond;

    }
    @RequestMapping(value = "/del")
    @ResponseBody
    public Respond del(@RequestParam(value = "ids[]" ) String[] ids){
        Respond respond = new Respond();
        try {
            logger.info("执行方法:{},执行时间:{}","del",LocalDateTimeUtils.getNowTime());
            for (int i = 0; i < ids.length ; i++) {
                countryService.updateStatusByPrimaryKey(ids[i]);
            }
            respond.setMsg("执行成功..");
        } catch (Exception e) {
            e.printStackTrace();
            respond.setCode(0);
            respond.setMsg("请求成功...");
            respond.setCount(0);
        }


        return respond;

    }
    /**
     * 
     * @params [id, model]
     * @return java.lang.String
     * @author SOS
     * @creed: Talk is cheap,show me the code
     * @date 2019/6/14 16:17
     */
    
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, Model model) {
        String key = "key_"+id;
        Country country = null;
        ValueOperations valueOperations = redisTemplate.opsForValue();
        if (redisTemplate.hasKey(key)) {
            logger.info("从Redis中获取key:{}",key);
            country = (Country) valueOperations.get(key);
        }else {
            logger.info("从数据库中获取key:{}",key);
            country = countryService.selectByPrimaryKey(id);
            valueOperations.set(key,country,30,TimeUnit.MINUTES);
        }
        model.addAttribute("country", country);
        return "/country/edit";
    }
    @RequestMapping("/add")
    public String add() {
        return "country/add";
    }

    @RequestMapping("/table")
    public String table() {
        return "country/table";
    }

    @RequestMapping("/save")
    @ResponseBody
    public Respond save(Country country) {
        Respond respond = new Respond();
        try {
            String code = UUID.randomUUID().toString();
            country.setCode(code);
            int i = countryService.insert(country);
            logger.info("{}",country);
            respond.setCode(200);
            respond.setMsg("添加成功.");
        } catch (Exception e) {
            e.printStackTrace();
            respond.setCode(500);
            respond.setMsg("添加失败.");
        }
        return respond;
    }

}
